package com.giveu.signature.common.util;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.TemplateEngineKind;

public class FreeMarkUtil {


	/**
	 * 通过路径 和文件名称后去魔板
	 *
	 * @param templateFilePath
	 * @param templateFileName
	 * @return
	 */
	public static Template getTemplate(String templateFilePath, String templateFileName) {
		try {
			Configuration cfg = new Configuration();
			cfg.setClassicCompatible(true);
			TemplateLoader templateLoader = new FileTemplateLoader(new File(
					templateFilePath));
			cfg.setTemplateLoader(templateLoader);
			return cfg.getTemplate(templateFileName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param templateFilePath
	 * @param templateFileName 加载的模板文件名
	 * @param replaceData
	 * @param outFile          生成指定文件
	 * @return 成功，返回文件名；失败，返回null。
	 */
	public static File tempRender(String templateFilePath, String templateFileName, Map<String, Object> replaceData) {
		String path =  System.getProperty("java.io.tmpdir")+File.separator+UUID.randomUUID().toString()+".html";
		File file = new File(path);
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file), "UTF-8"));
			Template temp = getTemplate(templateFilePath, templateFileName);
			temp.setEncoding("UTF-8");
			temp.process(replaceData, out);
		} catch (IOException e) {
			e.printStackTrace();
			path = null;
		} catch (TemplateException e) {
			e.printStackTrace();
			path = null;
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * freemarker渲染html
	 * @throws Exception 
	 */
	public static String tempRenderStr(String path,String htmlNmae,Map<String, Object> data) throws Exception {
		Writer out = new StringWriter();
		try {
			Configuration cfg = new Configuration();
			cfg.setClassicCompatible(true);
			cfg.setDirectoryForTemplateLoading(new File(path));
			Template template = cfg.getTemplate(htmlNmae);
			template.setEncoding("UTF-8");
			template.process(data, out);
			out.flush();
			return out.toString();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				out.close();
			} catch (IOException ex) {
			}
		}
	}
	
	  /** 
     * 解析模板 
     * 
     * @param configuration 
     * @param templateName 
     * @throws IOException 
     * @throws TemplateException 
     */  
	public static String renderStr(String templateHtml,Map<String, Object> map) throws Exception{  
		Writer out = new StringWriter();
		try {
			Configuration cfg = new Configuration();
			StringTemplateLoader templateLoader = new StringTemplateLoader();  
			cfg.setTemplateLoader(templateLoader);  
			cfg.setDefaultEncoding("UTF-8");  
			cfg.setClassicCompatible(true);
			Template template = new Template(UUID.randomUUID().toString(), templateHtml, cfg);  
			template.process(map, out);
			out.flush();
			return out.toString();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				out.close();
			} catch (IOException ex) {
			}
		}
    }  
	
	/** 
	 * 解析模板 
	 * 
	 * @param configuration 
	 * @param templateName 
	 * @throws IOException 
	 * @throws TemplateException 
	 * @throws XDocReportException 
	 */  
	public static File tempRenderDoc(String filePath,Map<String, Object> map) throws Exception{  
		String path =  System.getProperty("java.io.tmpdir")+File.separator+UUID.randomUUID().toString()+filePath.substring(filePath.lastIndexOf("."));;
		InputStream in = null;
		OutputStream out = null;
		try {
			File file = new File(path);
			if(!file.exists()){
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			in = new FileInputStream(filePath);
			IXDocReport report = XDocReportRegistry.getRegistry().loadReport(
					in, TemplateEngineKind.Freemarker);
			report.process(map, out);
			return file;
		} catch (Exception e) {
			throw e;
		}finally {
			try {
				out.close();
			} catch (IOException ex) {
			}
			try {
				in.close();
			} catch (IOException ex) {
			}
		}
	}  
	
	public static void main(String[] args) throws Exception {
		Map<String,Object> map = new HashMap<>();
//		map.put("data", "你好！");
		System.out.println(tempRenderDoc("C:\\Users\\520878\\Desktop\\test.docx", map).getAbsolutePath());
	}
  
}
